package com.example.exampleOS.slice;

import com.example.exampleOS.MainAbility;
import com.example.exampleOS.ResourceTable;
import com.example.rpxutil.RpxUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.distributedschedule.interwork.IInitCallback;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class MultiterminalSynergySlice  extends AbilitySlice {
    private static final String TAG = MainAbility.class.getSimpleName();
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);

    // 设备迁移

    //设备迁移
    // 流转应用包名
    // 当前应用包名
    // 流转应用包名
    private String REMOTE_BUNDLE_NAME = "com.example.exampleOS";
    // 流转FA名称
    private String REMOTE_FA_NAME = "com.example.exampleOS.slice.ClockCardSlice";
    // 流转PA名称
    private String BUNDLE_NAME = "com.example.exampleOS";
    // 注册流转任务管理服务后返回的Ability token
    private int abilityToken;
    // 用户在设备列表中选择设备后返回的设备ID
    private String selectDeviceId;
    // 用户是否已发起可拉回流转流程
    private boolean isReversibly = false;
    // 获取流转任务管理服务管理类
    private IContinuationRegisterManager continuationRegisterManager;
    // 设置初始化分布式环境的回调
    private IInitCallback iInitCallback = new IInitCallback() {
        @Override
        public void onInitSuccess(String deviceId) {
            HiLog.info(LABEL_LOG, "device id success: " + deviceId);
        }

        @Override
        public void onInitFailure(String deviceId, int errorCode) {
            HiLog.info(LABEL_LOG, "device id failed: " + deviceId + "errorCode: " + errorCode);
        }
    };
    // 设置流转任务管理服务设备状态变更的回调
    private IContinuationDeviceCallback callback = new IContinuationDeviceCallback() {

        @Override
        public void onDeviceConnectDone(String s, String s1) {
            selectDeviceId = s;
            continuationRegisterManager.updateConnectStatus(abilityToken,
                    selectDeviceId, DeviceConnectState.CONNECTED.getState(), null);
        }

        @Override
        public void onDeviceDisconnectDone(String s) {

        }

    };
    // 设置注册流转任务管理服务回调
    private RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void onResult(int result) {
            System.out.println("abilityToken result"+result);
            abilityToken = result;
        }
    };
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_multiterminalsynergy);
        initMigration();
        continuationRegisterManager = getContinuationRegisterManager();
    }
    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //设备迁移 start
        // 解注册流转任务管理服务
        continuationRegisterManager.unregister(abilityToken, null);
        // 断开流转任务管理服务连接
        continuationRegisterManager.disconnect();
        //设备迁移 end
    }
    // 注册流转任务管理服务
    private Component.ClickedListener mRegisterListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            HiLog.info(LABEL_LOG, "register call.");
            //增加过滤条件
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
            params.setJsonParams(jsonParams);
            System.out.println("BUNDLE_NAME"+BUNDLE_NAME);
            continuationRegisterManager.register(BUNDLE_NAME, params, callback, requestCallback);
        }
    };
    // 显示设备列表，获取设备信息
    private Component.ClickedListener mShowDeviceListListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            // 设置过滤设备类型
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
            params.setJsonParams(jsonParams);
            // 显示选择设备列表
            continuationRegisterManager.showDeviceList(abilityToken, params, null);
        }
    };
    // 跨端迁移FA 9。将运行时的FA迁移到目标设备，实现业务在设备间无缝迁移。
    private Component.ClickedListener mContinueAbilityListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            System.out.println("selectDeviceId"+selectDeviceId);
            if (selectDeviceId != null) {
                // 通过showDeviceList获取指定目标设备deviceId
                // 指定待启动FA/PA的bundleName和abilityName
                // 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId(selectDeviceId)
                        .withBundleName(REMOTE_BUNDLE_NAME)
                        .withAbilityName(REMOTE_FA_NAME)
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                Intent startIntent = new Intent();
                startIntent.setOperation(operation);
                // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
                startAbility(startIntent);
            } else {
                System.out.println("StartRemote selectDeviceId is null");
            }
        }
    };
    private Button createButton(String text, ShapeElement buttonBg) {
        Button button = new Button(this);
        // 建议开发者按照自己的界面进行按钮设计,示例代码仅供参考
        final int TEXT_SIZE = 50;
        button.setTextSize(TEXT_SIZE);
        button.setTextColor(Color.YELLOW);
        button.setText(text);
        button.setWidth(RpxUtil.rpx(336,this));
        button.setHeight(RpxUtil.rpx(215,this));
        button.setBackground(buttonBg);
        return button;
    }

    // 按照顺序在PositionLayout中依次添加按钮的示例
    private void addComponents( ShapeElement buttonBg) {
        // 构建显示注册流转任务管理服务的按钮
        Button btnRegister =(Button) findComponentById(ResourceTable.Id_multiterminalsynergyRegist);
        btnRegister.setBackground(buttonBg);
        btnRegister.setClickedListener(mRegisterListener);

        // 构建显示设备列表的按钮
        Button btnShowDeviceList =(Button) findComponentById(ResourceTable.Id_multiterminalsynergyShow);
        btnShowDeviceList.setBackground(buttonBg);
        btnShowDeviceList.setClickedListener(mShowDeviceListListener);

        // 构建跨端迁移FA的按钮
        Button btnContinueRemoteFA =(Button) findComponentById(ResourceTable.Id_multiterminalsynergyFA);
        btnContinueRemoteFA.setBackground(buttonBg);
        btnContinueRemoteFA.setClickedListener(mContinueAbilityListener);
        // 构建可拉回迁移FA的按钮
//        Button btnContinueReversibly = createButton("ContinueReversibly", buttonBg);
//        btnContinueReversibly.setClickedListener(mContinueReversiblyListener);
//        linear.addComponent(btnContinueReversibly);

        // 构建拉回FA的按钮
//        Button btnReverseContinue = createButton("ReverseContinuation", buttonBg);
//        btnReverseContinue.setClickedListener(mReverseContinueListener);
//        linear.addComponent(btnReverseContinue);
    }
    private void initMigration(){

        ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
                ComponentContainer.LayoutConfig.MATCH_PARENT);
        ShapeElement buttonBg = new ShapeElement();
        buttonBg.setRgbColor(new RgbColor(0, 125, 255));
        addComponents(buttonBg);
    }
    //    设备迁移 end
}
